package com.initialize.auth.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.initialize.common.mybatis.plus.entity.User;
import com.initialize.common.tool.jwt.JwtTokenTool;
import com.initialize.service.api.system.feign.IUserClient;
import com.initialize.service.api.system.model.LoginModel;
import com.initialize.service.api.system.resttemplate.IUserRestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

/**
 * Created with IntelliJ IEA.
 * User: jane
 * Date: 2019/12/25
 * Time: 8:22 下午
 * Description:
 */
@Slf4j
@RestController
@RequestMapping("auth")
public class AuthController {


    final
    IUserClient iUserClient;

    final
    IUserRestTemplate iUserRestTemplate;

    public AuthController(IUserClient iUserClient,
                          IUserRestTemplate iUserRestTemplate) {
        this.iUserClient = iUserClient;
        this.iUserRestTemplate = iUserRestTemplate;
    }

    /**
     * 为制定的用户创建token
     *
     * @param loginModel
     * @return
     */
    @PostMapping(value = "/create-token")
    public R<String> CreateToken(@RequestBody LoginModel loginModel) {
        User byUsername = iUserRestTemplate.login(loginModel.getLoginName());
//        User byUsername = iUserClient.login(loginModel.getLoginName());

        if (Objects.isNull(byUsername)) {
            return R.failed("认证失败-100");
        } else {
            String uPsd = byUsername.getUPsd();
            String modelPassWord = loginModel.getPassWord();
            log.info("uPsd->>  {},  modelPassWord->>  {}",uPsd,modelPassWord);
            boolean matches = new BCryptPasswordEncoder().matches(modelPassWord, uPsd);
            if (matches) {
                String s = JwtTokenTool.createToken(byUsername.getId(), byUsername.getULogin(), byUsername.getUPsd());
                return R.ok(s);
            }
        }
        return R.failed("认证失败-101");
    }

    /**
     * 获取token的失效时间
     *
     * @param token
     * @return
     */
    @GetMapping(value = "/expire-date")
    public R<String> getTOKENExpirationTime(String token) {
        Date expirationDateFromToken = JwtTokenTool.getTheExpirationTime(token);
        String s = DateUtil.formatDateTime(expirationDateFromToken);
        return R.ok(s);
    }
}